package com.hs.srm.admin.modules.warehouse.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.common.util.OANoticeUtil;
import com.hs.srm.admin.modules.orders.entity.ScmPoItemEntity;
import com.hs.srm.admin.modules.orders.entity.StockEntity;
import com.hs.srm.admin.modules.orders.service.StockService;
import com.hs.srm.admin.modules.requisition.controller.ProPurchRequetSapTask;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestHeaderEntity;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestHeaderService;
import com.hs.srm.common.utils.DateUtils;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import com.sap.conn.jco.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author socik
 * @date 2019/5/9 9:38
 * @email socik@qq.com
 */
@Component("stockSapTask")
public class StockSapTask {

    @Autowired
    private StockService stockServiceImpl;

    @Autowired
    NproPurchRequestHeaderService nproPurchRequestHeaderService;


    Logger logger = LoggerFactory.getLogger(ProPurchRequetSapTask.class);

    /**
     * @Description sap到srm收获接口
     * @Param []
     * @Return void
     * @Author socik
     * @Date 2019/5/9 9:43
     */
    public void stockSap() {
        logger.debug("收货接口开始启动!");
        StockEntity stockEntity;
        //对同一订单同一行项目的入库数据合并发货数量，避免显示多条
        List<StockEntity> stockEntityList = new ArrayList<>();
        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList list = null;
        //调用SAP接口
        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZPUR_POSTINFO_SAP_TO_SRM");
            list = function.getTableParameterList();

        } catch (JCoException e) {
            e.printStackTrace();
        }
        //传入过账日期和公司代码
        JCoTable jCoFieldsTable = list.getTable("R_BUDAT");
        jCoFieldsTable.appendRow();
        jCoFieldsTable.setValue("SIGN", "I");
        jCoFieldsTable.setValue("OPTION", "BT");
        //查询数据，开始时间设定昨天
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -2);
        jCoFieldsTable.setValue("LOW", format.format(calendar.getTime()));
        jCoFieldsTable.setValue("HIGH", "99999999");
        try {
            function.execute(destination);
        } catch (JCoException e) {
            e.printStackTrace();
        }
        //得到sap返回表数据
        JCoTable returnTable = list.getTable("OUT_TAB");
        //循环SAP返还数据
        if (returnTable.getNumRows() > 0) {
            for (int x = 0; x < returnTable.getNumRows(); x++) {
                returnTable.setRow(x);
                //是否同步过
                String sync_stat = returnTable.getString("SYNC_STAT");
                //同步过的数据不再保存
                if (sync_stat.equals("S")) {
                    continue;
                }
                stockEntity = new StockEntity();
                //创建时间
                stockEntity.setCreateTime(new Date());
                stockEntity.setPoNo(returnTable.getString("EBELN"));
                stockEntity.setItemNo(returnTable.getString("EBELP"));
                stockEntity.setShippedQty(new BigDecimal(returnTable.getString("BPMNG")));
                stockEntity.setDeliverNo(returnTable.getString("GUID32"));
                stockEntity.setMblnr(returnTable.getString("MBLNR"));
                stockEntity.setZeile(returnTable.getString("ZEILE"));
                //入库时间
                stockEntity.setStockTime(DateUtils.stringToDate(returnTable.getString("CRDAT"), DateUtils.DATE_PATTERN));
                //品管 验货在sap
                stockEntity.setStatus(4);
                String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                stockEntity.setPkId(uuid);
                sendOaMessage(stockEntity);
                int i;
                for (i = 0; i < stockEntityList.size(); i++) {
                    //poNo相同，itemNo相同，即表示为同一订单行项目
                    if (stockEntity.getPoNo().equals(stockEntityList.get(i).getPoNo()) && stockEntity.getItemNo().equals(stockEntityList.get(i).getItemNo())) {
                        //同一订单行项目数量累加
                        stockEntityList.get(i).setShippedQty(stockEntityList.get(i).getShippedQty().add(stockEntity.getShippedQty()));
                        break;
                    }
                }
                //list中不包含stockEntity，添加到list
                if (i == stockEntityList.size()) {
                    stockEntityList.add(stockEntity);
                }
                //调用SAP接口
                try {
                    function = destination.getRepository().getFunction("ZPUR_POSTINFO_SRM_TO_SAP");
                    list = function.getTableParameterList();
                } catch (JCoException e) {
                    e.printStackTrace();
                }
                JCoTable intab = list.getTable("IN_TAB");
                intab.appendRow();
                intab.setValue("GUID32", stockEntity.getDeliverNo());
                try {
                    function.execute(destination);
                } catch (JCoException e) {
                    e.printStackTrace();
                }
                logger.info("收货记录同步成功订单号:" + stockEntity.getPoNo() + "行项目" + stockEntity.getItemNo());
            }
            //插入数据，返回SAP以获取记录
            if (stockEntityList.size() > 0) {
                stockServiceImpl.insertBatch(stockEntityList);
            }
        } else {
            logger.debug("SAP无收获数据更新!");
        }
    }

    /**
     * @Description 发送OA入库通知
     * @Param [stockEntity]
     * @Return boolean
     * @Author socik
     * @Date 2019/11/4 11:10
     */
    public boolean sendOaMessage(StockEntity stockEntity) {
        ScmPoItemEntity scmPoItemEntity = OANoticeUtil.selectCodeByPoItem(stockEntity.getPoNo(), stockEntity.getItemNo());
        if (scmPoItemEntity == null) {
            return false;
        }
        //获取下单人OA账号，非生产性,生产性不需要通知
        NproPurchRequestHeaderEntity headerEntity = nproPurchRequestHeaderService.selectOne(
                new EntityWrapper<NproPurchRequestHeaderEntity>()
                        .eq("purch_request_code", scmPoItemEntity.getPrNo()));
        if (headerEntity == null || StringUtils.isBlank(headerEntity.getOAccount())) {
            return false;
        }
        String OAccount = headerEntity.getOAccount();
        try {
            return OANoticeUtil.remind(scmPoItemEntity.getPrNo(), "您申请的: " + scmPoItemEntity.getMaterialDesc() + " 已经入库", "到货通知", true);
        } catch (Exception_Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}